﻿using System;
using System.Collections.Generic;
using System.Web;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

namespace PDFConverterTest.Convertors
{
    public class ExcelPDFConvertor:IPDFConvertor
    {
        #region Ctor

        public ExcelPDFConvertor()
        {
            Application = new Excel.ApplicationClass();
        }

        #endregion

        #region  Properties

        public Excel.Application Application
        {
            get;
            protected set;
        }

        #endregion

        #region IPDFConvertor Interface

        public void ConvertToPDF(string fileFullName)
        {
            int index = fileFullName.LastIndexOf(".");
            if (index > -1)
            {
                string pdfFullName = fileFullName.Substring(0, index) + PDFConvertorConstants.PDFFormat;
                ConvertToPDF(fileFullName, pdfFullName);
            }
        }

        public void ConvertToPDF(string fileFullName, string pdfFullName)
        {
            Excel.Workbook workBook = null;
            try
            {
                int index = fileFullName.LastIndexOf(".");
                string fileExtension = fileFullName.Substring(index, fileFullName.Length - index); 
                object openFileFormat = PDFConvertorFactory.GetOpenFileFormat<ExcelPDFConvertor>(fileExtension);
                object openMissing = Type.Missing;
                workBook = Application.Workbooks.Open(fileFullName, openMissing, openMissing, openMissing, openMissing, openMissing,
                        openMissing, openMissing, openMissing, openFileFormat, openMissing, openMissing, openMissing, openMissing, openMissing);

                if (workBook != null)
                {
                    object saveFileName = fileFullName.Substring(0, index) + PDFConvertorConstants.PDFFormat;
                    object saveFileForamt = PDFConvertorFactory.GetSaveFileFormat<ExcelPDFConvertor>(fileExtension);
                    object saveMissing = Type.Missing; 
                    workBook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, saveFileName, saveMissing, saveMissing, saveMissing, saveMissing, saveMissing, saveMissing, saveMissing);
                    workBook.Close(); 
                } 
            }
            catch (Exception error)
            {
            }
            finally
            {
                Marshal.ReleaseComObject(workBook);
                GC.Collect();
            }
        }

        public void Dispose()
        {
            Marshal.ReleaseComObject(Application);
            GC.Collect();
        }

        #endregion
    }
}